<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace api\user\controller;

use api\user\model\UserOrderModel;
use cmf\controller\RestBaseController;
use think\Db;
use api\common\model\WXPay;
use api\common\model\WXPayConstants;
use api\common\model\WXPayUtil;
use think\Log;
use think\Loader;

class OrderController extends RestBaseController
{
		protected $orderModel;
		private $wxpay;
    private $appId = 'wx9cd82031f1039ced';
    private $mchId = '1354832902';
    private $apiKey = 'A44BC3DDC578B122F58D1B91636C622h';

    public function __construct(UserOrderModel $orderModel)
    {
        parent::__construct();
        $this->orderModel = $orderModel;
				$this->wxpay = new WXPay(
								$this->appId,
								$this->mchId,
								$this->apiKey,
								'/www/wwwroot/tsxcxht/cert/apiclient_cert.pem',
								'/www/wwwroot/tsxcxht/cert/apiclient_key.pem',
							6000);  // 超时时间，毫秒
    }

    // 掉起支付
    public function pay()
    {
		// 获取open_id
		$openid = $this->_getOpenid();
		if(empty($openid)){
			$this->error('获取用户openid失败');
		}

		// 生成商户订单
		$userId = $this->getUserId();

    $param  = $this->request->param();
		if(empty($param['amount'])){
			$this->error('参数错误');
		}

		$amount = floatval($param['amount']);
		if($amount <= 0 || $amount >= 1000){
			$this->error('支付金额错误');
		}

		$data['order_no'] = strval(time()).'_'.strval($this->getUserId()).'_'.rand(100,999);
		$data['user_id'] = $userId;
		$data['total_money'] = intval($amount*100);
		$data['create_time'] = time();
		$orderId = $this->orderModel->addOrder($data);
        if(!$orderId) {
            $this->error('生成商户订单失败');
        }else{
			Log::error(json_encode($orderId));
		}

		// 调用支付统一下单API
		$reqData['body'] = '打赏'.$amount.'元';
		$reqData['out_trade_no'] = $data['order_no'];
		$reqData['total_fee'] = intval($amount*100);
		$reqData['spbill_create_ip'] = '118.25.44.197';
		$reqData['notify_url'] = 'https://ytld.xgtxcx.com/api/user/paynotify';
		$reqData['trade_type'] = 'JSAPI';
		$reqData['openid'] = $openid;
		$resp = $this->wxpay->unifiedOrder($reqData);

		// 将组合数据再次签名
		if($resp['return_code'] == 'SUCCESS' && $resp['return_msg'] == 'OK'){
			$rawData['appId'] = $resp['appid'];
			$rawData['timeStamp'] = time();
			$rawData['nonceStr'] = WXPayUtil::generateNonceStr();
			$rawData['package'] = 'prepay_id='.$resp['prepay_id'];
			$rawData['signType'] = 'MD5';
			$rawData['sign'] = WXPayUtil::generateSignature($rawData, $this->apiKey);
			$this->success('请求成功', $rawData);
		}else{
			unset($data);
			$data['return_code'] = $resp['return_code'];
			$data['return_msg'] = $resp['return_msg'];
			$where['id'] = $orderId;
			$this->orderModel->updateOrder($data,$where);
		}
    }

	// 支付回调
	public function paynotify()
	{
		$xml = file_get_contents("php://input");
		Log::error($xml);
		if(isset($xml)){
			$xmlData = WXPayUtil::xml2array($xml);
			Log::error(json_encode($xmlData));

			if($this->wxpay->isPayResultNotifySignatureValid($xmlData)){
				$where['order_no'] = $xmlData['out_trade_no'];
				$where['total_money'] = $xmlData['total_fee'];
				$where['is_paid'] = 0;
				$data['is_paid'] = 1;
				$data['pay_time'] = time();
				$data['transaction_id'] = $xmlData['transaction_id'];
				$data['return_code'] = 'SUCCESS';
				$data['return_message'] = $xml;
				if($this->orderModel->updateOrder($data,$where)){
					$retData['return_code'] = 'SUCCESS';
					$retData['return_msg'] = 'OK';
				}else{
					$retData['return_code'] = 'FAIL';
					$retData['return_msg'] = '更新数据库出错';
				}
			}else{
				$where['order_no'] = $xmlData['out_trade_no'];
				$data['return_code'] = 'FAIL';
				$data['return_message'] = '[签名校验错误]'.$xml;
				$this->orderModel->updateOrder($data,$where);
				$retData['return_code'] = 'FAIL';
				$retData['return_msg'] = '签名校验错误';
			}

			return WXPayUtil::array2xml($retData);
		}else{
			$retData['return_code'] = 'FAIL';
			$retData['return_msg'] = '未接收到XML';
			return WXPayUtil::array2xml($retData);
		}
	}

	// 获取open_id
	private function _getOpenid()
	{
		$where['user_id'] = $this->getUserId();
		$where['third_party'] = 'wxapp';
		$where['status'] = 1;
		$where['app_id'] = $this->appId;

		$result = Db::name('third_party_user')->where($where)->select();
		if(empty($result)){
			return '';
		}else{
			return $result[0]['openid'];
		}
	}
}
